import logging
import os
import sys
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from flask import Blueprint, Flask, session
from werkzeug.wrappers.request import Request
from flask_cors import CORS
import uuid

from api.db import StatusEnum
from api.db.db_models import close_connection
from api.db.services import UserService
from api.utils import CustomJSONEncoder, commands

from flask_session import Session
from flask_login import LoginManager
from api.settings import SECRET_KEY, stat_logger
from api.settings import API_VERSION, access_logger
from api.utils.api_utils import server_error_response
from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer

__all__ = ['app']

logger = logging.getLogger('flask.app')
for h in access_logger.handlers:
    logger.addHandler(h)

Request.json = property(lambda self: self.get_json(force=True, silent=True))

app = Flask(__name__)
CORS(app, supports_credentials=True, max_age=2592000)
app.url_map.strict_slashes = False
app.json_encoder = CustomJSONEncoder
app.errorhandler(Exception)(server_error_response)

## Convenience for dev and debug
# app.config["LOGIN_DISABLED"] = True
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['MAX_CONTENT_LENGTH'] = int(os.environ.get("MAX_CONTENT_LENGTH", 128 * 1024 * 1024))

Session(app)
login_manager = LoginManager()
login_manager.init_app(app)

commands.register_commands(app)


def search_pages_path(pages_dir):
    app_path_list = [path for path in pages_dir.glob('*_app.py') if not path.name.startswith('.')]
    api_path_list = [path for path in pages_dir.glob('*_api.py') if not path.name.startswith('.')]
    app_path_list.extend(api_path_list)
    return app_path_list


def register_page(page_path):
    path = f'{page_path}'

    # 根据文件名确定 page_name
    page_name = page_path.stem.rstrip('_api') if "_api" in path else page_path.stem.rstrip('_app')
    module_name = '.'.join(page_path.parts[page_path.parts.index('api'):-1] + (page_name,))

    # 动态加载模块
    spec = spec_from_file_location(module_name, page_path)
    page = module_from_spec(spec)
    page.app = app
    page.manager = Blueprint(page_name, module_name)
    sys.modules[module_name] = page
    spec.loader.exec_module(page)
    page_name = getattr(page, 'page_name', page_name)
    unique_blueprint_name = ''
    # 判断路径中是否包含 'admin' 或 'common' 目录
    if 'admin' in page_path.parts:
        prefix = f'/admin'
        unique_blueprint_name = f'admin/{page_name}'
    elif 'common' in page_path.parts:
        prefix = f'/common'
        unique_blueprint_name = f'common/{page_name}'
    else:
        prefix = ''
        unique_blueprint_name = f'apps/{page_name}'
    # 设置 URL 前缀，根据是否在 api、admin 或 common 目录来决定
    url_prefix = f'/api/{API_VERSION}{prefix}/{page_name}' if "_api" in path else f'/{API_VERSION}{prefix}/{page_name}'

    # 为蓝图生成唯一名称，防止冲突

    print(f'Registering blueprint for {unique_blueprint_name} at {url_prefix}')  # 调试信息

    # 注册 Blueprint
    app.register_blueprint(page.manager, url_prefix=url_prefix, name=unique_blueprint_name)
    return url_prefix


pages_dir = [
    Path(__file__).parent,  # 当前目录
    Path(__file__).parent.parent / 'apps' / 'admin',  # api/apps/admin 目录
    Path(__file__).parent.parent / 'apps' / 'common',  # api/apps/common 目录
]

client_urls_prefix = [
    register_page(path)
    for dir in pages_dir
    for path in search_pages_path(dir)
]


@login_manager.request_loader
def load_user(web_request):
    jwt = Serializer(secret_key=SECRET_KEY)
    authorization = web_request.headers.get("Authorization")
    if authorization:
        try:
            access_token = str(jwt.loads(authorization))
            user = UserService.query(access_token=access_token, status=StatusEnum.VALID.value)
            if user:
                user[0].tenant_id = session.get('tenant_id')
                user[0].user_tenant = session.get('user_tenant')
                user[0].user_knowledge = session.get('user_knowledge')
                return user[0]
            else:
                return None
        except Exception as e:
            stat_logger.exception(e)
            return None
    else:
        return None


@app.teardown_request
def _db_close(exc):
    close_connection()